import React,{useState,useEffect} from 'react';
import {message, Modal, Table} from "antd";
import axios from "axios";
import {get, post} from "../../../service";

function RelateModalForm(props) {
    const [dataSource,setDataSource]=useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onCancel=()=>{
        props.dispatch({
            type:'hideRelateModalForm'
        })
    }
    useEffect(() => {
        get('/api/user/relateMenus').then(res=>{
            setDataSource(res.data.records)
        })
        return () => {

        };
    }, []);

    const onSave=()=>{
       post('/api/user/updateRelateMenus',{
           relatedMenus:selectedRowKeys.join(','),
           id:props.data.id
       }).then(res=>{
           message.success('关联成功')
           onCancel()
           props.refreshList()
       })
    }
    const getTableProps=()=>({
        rowKey:'id',
        columns:[
            {
                title:'菜单',
                dataIndex:'name',
            },
            {
                title:'菜单',
                dataIndex:'linkUrl',
            }
        ],
        dataSource:dataSource,
        pagination:false,
        rowSelection:{
            defaultSelectedRowKeys:props.data.relatedMenus?props.data.relatedMenus.split(',').map(item=>item-0):[],
            checkStrictly:false,
            onChange:(selectedRowKeys,selectedRows)=>{
                setSelectedRowKeys(selectedRowKeys)
            }
        }
    })
    return (
        <Modal visible width={600} title={props.title} onCancel={onCancel} onOk={onSave}>
            <Table {...getTableProps()}/>
        </Modal>
    );
}

export default RelateModalForm;
